package com.itheima.sso.service.impl;


import com.itheima.model.common.pojos.User;
import com.itheima.model.common.utils.AppJwtUtil;
import com.itheima.model.common.utils.ThreadLocalUtil;
import com.itheima.sso.doman.vo.UserInfoVo;
import com.itheima.sso.mapper.UserMapper;
import com.itheima.sso.service.LoginService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserMapper userMapper;

    @Override
    public User checkToken(String token) {

        Claims claims = AppJwtUtil.getClaimsBody(token);

        int i = AppJwtUtil.verifyToken(claims);
        if (i > 0) {
            throw new RuntimeException("无效的token");
        }
        // 从 Claims 中获取用户 ID
        Object id = claims.get("id");

        if (id == null) {
            throw new RuntimeException("Token 中未找到用户 ID");
        }

        User user = userMapper.getById(id.toString());

        if (user != null) {
            ThreadLocalUtil.setUser(user);
            return user;

        }
        return null;
    }

    @Override
    public UserInfoVo login(User user) {
//        查询数据库获取用户信息
        User users = userMapper.getUser(user);

        long uid = (long) users.getUid();

        if (users == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        String token = AppJwtUtil.getToken(uid);
        //封装vo
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUser(users);
        userInfoVo.setTotal(token);
        return userInfoVo;
    }
}
